package com.wtb.javatool.service.impl;

import com.wtb.javatool.common.PageBean;
import com.wtb.javatool.dao.AssignmentMapper;
import com.wtb.javatool.dao.TaskMapper;
import com.wtb.javatool.dao.UndertakerMapper;
import com.wtb.javatool.dto.AssignmentDto;
import com.wtb.javatool.dto.StudentGradeDto;
import com.wtb.javatool.entity.Assignment;
import com.wtb.javatool.service.AssignmentService;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class AssignmentServiceImpl implements AssignmentService {
    private final AssignmentMapper assignmentMapper;
    private final UndertakerMapper undertakerMapper;
    private final TaskMapper taskMapper;

    public AssignmentServiceImpl(AssignmentMapper assignmentMapper, UndertakerMapper undertakerMapper, TaskMapper taskMapper) {
        this.assignmentMapper = assignmentMapper;
        this.undertakerMapper = undertakerMapper;
        this.taskMapper = taskMapper;
    }

    /**
     * 为任务新增分配记录和承担者
     *
     * @param assignment 分配记录
     * @param userIdList 被分配者的ID列表
     */
    public void addAssignmentAndUndertaker(Assignment assignment, List<Long> userIdList) {
        assignmentMapper.addAssignment(assignment);

        if (!userIdList.isEmpty()) {
            undertakerMapper.addUndertakers(assignment.getAssignmentId(), userIdList);
        }
    }

    /**
     * 查询某个任务下的所有分配记录
     *
     * @param taskId      任务ID
     * @param projectType 项目类型
     * @return 返回分配记录列表
     */
    public List<AssignmentDto> findAssignmentsByTaskId(Long taskId, Integer projectType) {
        if (projectType != 2) {
            return assignmentMapper.findNormalAssignmentsByTaskId(taskId);
        } else {
            return assignmentMapper.findTeachingAssignmentsByTaskId(taskId);
        }

    }

    /**
     * 根据分配记录ID列表删除对应分配记录(将状态值改为4）
     *
     * @param assignmentId 分配记录ID
     */
    @Override
    public void deleteAssignmentByAssignmentId(List<Long> assignmentId) {
        assignmentMapper.deleteAssignmentByAssignmentId(assignmentId);
    }

    /**
     * 修改任务分配记录状态
     *
     * @param assignmentsIds   分配记录id列表
     * @param assignmentStatus 任务状态 （0：待领取,1:进行中，2待验收，3已完成）
     */
    public void updateAssignmentStatusByAssignmentId(List<Long> assignmentsIds, Integer assignmentStatus) {
        assignmentMapper.updateAssignmentStatusByAssignmentId(assignmentsIds, assignmentStatus);
    }

    /**
     * 更新单个分配记录的截止日期
     *
     * @param assignment 分配记录实体 （包含assignmentId和endTime和teamId）
     */
    public void updateAssignmentEndTimeAndTeamByAssignmentId(Assignment assignment) {
        assignmentMapper.updateAssignmentEndTimeAndTeamIdByAssignmentId(assignment);
    }

    /**
     * 更新多个分配记录的截止日期
     *
     * @param assignmentIdList 分配记录id列表
     * @param endTime          截止日期
     */
    public void updateAssignmentsEndTimeByAssignmentIds(List<Long> assignmentIdList, Date endTime) {
        assignmentMapper.updateAssignmentsEndTimeByAssignmentIds(assignmentIdList, endTime);
    }

    /**
     * 增删查改某个分配记录中的承担者。
     *
     * @param assignmentId 分配记录ID
     * @param userIdList   用户ID列表。。
     */
    public void upsertDeleteAssignmentUndertakers(Long assignmentId, List<Long> userIdList) {
        //获取当前分配记录的所有承担者ID
        List<Long> initialUserIdList = assignmentMapper.findAssignmentUndertakerIdsByAssignmentId(assignmentId);

        // 遍历前端用户列表进行更新和插入
        for (Long UserId : userIdList) {
            //判断当前ID是否存在已有的分配记录中
            boolean isNotInList = !initialUserIdList.contains(UserId);
            if (isNotInList) {
                //若无重复ID，则插入未重复的ID
                undertakerMapper.insertAssignmentUndertakerByAssignmentId(assignmentId, UserId);
            } else {
                // 若有重复ID，则排除出去
                initialUserIdList.remove(UserId);
            }
        }
        // 删除剩余ID
        for (Long userId : initialUserIdList) {
            undertakerMapper.deleteAssignmentUndertakerByAssignmentId(assignmentId, userId);
        }
    }

    /**
     * 根据项目ID,返回该项目下所有任务的分配记录。
     *
     * @param projectId        项目ID
     * @param assignmentStatus 分配记录状态
     * @param taskType         任务类型
     * @param courseId         课程ID
     * @param projectType      项目类型
     * @return 返回记录状态的列表。
     */
    public List<AssignmentDto> findTasksAssignments(Long projectId, Integer assignmentStatus, Integer taskType, Long courseId, Integer projectType) {
        //获取全部任务ID
        List<Long> taskIdList = taskMapper.findTasksIdByProjectId(projectId);
        if (projectType == 1) {
            return assignmentMapper.findNormalTasksAssignments(taskIdList, assignmentStatus, taskType, courseId);
        } else {
            return assignmentMapper.findTeachingTasksAssignments(taskIdList, assignmentStatus, taskType, courseId,2);

        }
    }

    /**
     * 根据课程ID,返回该课程下关联的任务的分配记录的状态数量。
     *
     * @param courseId 课程ID
     * @return 返回记录状态数量的列表，依次为分配总数、已完成、进行中、未开始、延期、未批阅。
     */
    public AssignmentDto findTaskAssignmentNumberByCourseId(Long courseId,Integer evaluationType) {

        List<Long> taskIds = taskMapper.findTaskIdsByCourseId(courseId);
        if (taskIds.isEmpty()) {
            AssignmentDto assignmentDto = new AssignmentDto();
            assignmentDto.setCompleted(0);
            assignmentDto.setExtension(0);
            assignmentDto.setTotal(0);
            assignmentDto.setNotStarted(0);
            assignmentDto.setNotReviewed(0);
            assignmentDto.setInProgress(0);
            return assignmentDto;
        } else return assignmentMapper.findAssignmentNumberByTasksId(taskIds,evaluationType);
    }

    @Override
    public PageBean<StudentGradeDto> findCourseGrades(Long courseId, Long classId, Long teamId,
                                                   String studentName, String studentMajor,
                                                   Integer currentPage, Integer pageSize) {
        // 创建分页对象
        PageBean<StudentGradeDto> pageBean = new PageBean<>();
        
        try {
            // 查询符合条件的学生列表
            List<StudentGradeDto> studentGrades = assignmentMapper.findCourseGrades(
                courseId, classId, teamId, studentName, studentMajor, currentPage * pageSize, pageSize);
            
            // 查询符合条件的学生总数
            Integer totalCount = assignmentMapper.countCourseGrades(
                courseId, classId, teamId, studentName, studentMajor);
            
            // 设置分页数据
            pageBean.setRows(studentGrades);
            pageBean.setTotalCount(totalCount);
            
            return pageBean;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取课程成绩数据失败: " + e.getMessage(), e);
        }
    }

    @Override
    public String exportCourseGrades(Long courseId) {
        try {
            // 查询所有学生成绩数据（不分页）
            List<StudentGradeDto> studentGrades = assignmentMapper.findCourseGrades(
                courseId, null, null, null, null, null, null);
            
            if (studentGrades == null || studentGrades.isEmpty()) {
                throw new RuntimeException("没有可导出的成绩数据");
            }
            
            // TODO: 实现导出Excel文件的逻辑
            // 这里应该实现将studentGrades数据导出为Excel文件，并返回文件URL
            // 由于这里需要具体的文件操作实现，暂时返回一个示例URL
            
            return "/export/course_" + courseId + "_grades.xlsx";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出课程成绩数据失败: " + e.getMessage(), e);
        }
    }
}
